package cn.gp.controller.exception;

import cn.gp.common.Code;
import cn.gp.common.R;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @ClassName GlobalExceptionAdvice
 * @Description TODO
 * @Author He_Guoping
 * @Date 2023/5/31 12:53
 * @Version 1.0
 */
@Log4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionAdvice {

    /**
     *@Description 重复插入sql异常
     *@param ex
     *@Return cn.gp.common.R<java.lang.String>
     *@Author He_Guoping
     *@Date 13:00 2023/5/31
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split("\\s+");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> customException(CustomException ex) {
        log.info(ex.getMessage());
        return new R<>(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(SystemException.class)
    public R<String> systemException(SystemException ex) {
        log.info(ex.getMessage());
        return new R<>(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception ex) {
        return new R<>(Code.SYSTEM_UNKNOW_ERR, "系统繁忙");
    }
}
